package permissions

import (
	"context"
	"errors"
	"product/common/datetime"
	"product/common/validator"

	"product/authorization/serve/internal/svc"
	"product/authorization/serve/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type QueryPermissionsLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 查询权限
func NewQueryPermissionsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QueryPermissionsLogic {
	return &QueryPermissionsLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *QueryPermissionsLogic) QueryPermissions(req *types.QueryPermissionListReq) (resp []types.PermissionInfo, err error) {
	valid, err := validQueryPermissionsInput(req)
	if !valid && err != nil {
		return nil, err
	}
	conditions := make(map[string]interface{})
	if !validator.IsEmptyString(req.Name) {
		conditions["PermissionName"] = req.Name
	}
	list, err := l.svcCtx.PermissionsModel.FindPermissions(l.ctx, int64(req.Page), int64(req.PageSize), conditions)
	if err != nil {
		return nil, err
	}
	var data []types.PermissionInfo
	for _, item := range list {
		data = append(data, types.PermissionInfo{
			Id:         item.ID,
			Name:       item.PermissionName,
			Value:      int(item.PermissionValue),
			CreateTime: datetime.NewUnix(item.CreatedAt).ToFormatByTp(datetime.YearMouthDayHourMinute),
			UpdateTime: datetime.NewUnix(item.UpdatedAt).ToFormatByTp(datetime.YearMouthDayHourMinute),
			Desc:       item.Description.String,
		})
	}
	return data, nil
}

func validQueryPermissionsInput(req *types.QueryPermissionListReq) (bool, error) {
	if req.Page == 0 {
		return false, errors.New("page参数不能为空")
	}
	if req.PageSize == 0 {
		return false, errors.New("pageSize参数不能为空")
	}
	return true, nil
}
